import { defineStore } from "pinia";
import { Goods } from "@/entity/Goods";
import { getCartList } from "@/api/cart";

export const useCartStore = defineStore("cart", {
  state: () => ({
    // 购物车列表
    cartList: [] as Goods[],
  }),

  getters: {
    // 商品类型总数
    typeCount: (state) => state.cartList.length,
    // 商品总数
    count(state) {
      return state.cartList.reduce((prev, item) => prev + item.number, 0);
    },
    // 根据 id 获取购物车
    getCartById(state) {
      return (goodsId) =>
        state.cartList.find((item) => item.goodsId === goodsId);
    },
  },

  actions: {
    // 增加购物车
    addCart(goods: Goods) {
      goods = Object.assign({}, goods);
      const cartList = this.cartList as Goods[];

      const findGoods = cartList.find((item) => item.goodsId === goods.goodsId);

      if (findGoods) {
        findGoods.number++;
      } else {
        goods.number = goods.number > 1 ? goods.number : 1;
        cartList.push(goods);
      }
    },
    // 减少购物车
    reduceCart(goods: Goods) {
      const cartList = this.cartList as Goods[];

      const findGoodsIndex = cartList.findIndex(
        (item) => item.goodsId === goods.goodsId
      );
      const findGoods = cartList[findGoodsIndex];

      if (findGoods) {
        if (findGoods.number > 1) {
          // 如果数量大于 1 就减少
          findGoods.number--;
        } else {
          // 数量小于等于 1 就删除
          cartList.splice(findGoodsIndex, 1);
        }
      }
    },
    // 删除购物车
    removeCart(goods: Goods) {
      const cartList = this.cartList as Goods[];

      const findGoodsIndex = cartList.findIndex(
        (item) => item.goodsId === goods.goodsId
      );

      cartList.splice(findGoodsIndex, 1);
    },
    // 获取购物车列表
    async getCartList(...args: Parameters<typeof getCartList>) {
      const cartList = this.cartList as Goods[];

      const res = await getCartList(...args);

      if (!cartList.length) {
        this.cartList = res;
      }
    },
  },
});
